package com.qianda.qdminiapp.security;

import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 认证器，用于认证用户是否合法
 * @ClassName AuthenticationProvider
 * @Author cw
 * @Date 2019/7/1 10:26
 **/
public class AuthenticationProvider  extends AbstractUserDetailsAuthenticationProvider {

    private final UserDetailsService service;
    private final PasswordEncoder passwordEncoder;

    /**
     * @param service
     * @param passwordEncoder
     */
    public AuthenticationProvider(UserDetailsService service, PasswordEncoder passwordEncoder) {
        if (service == null) {
            throw new IllegalArgumentException("UserDetailsService is required");
        }
//        if (passwordEncoder == null) {
//            throw new IllegalArgumentException("PasswordEncoder is required");
//        }
        this.service = service;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected void additionalAuthenticationChecks(
            UserDetails userDetails,
            UsernamePasswordAuthenticationToken authRequest) throws AuthenticationException {

        // 可以在此处检查密码
//        String requestPassword = (String) authRequest.getCredentials();
//
//        if (!passwordEncoder.matches(requestPassword, userDetails.getPassword())) {
//            // throw new SimpleException(ExceptionCode.EX_HTTP_ACCESS_DENIED);
//
//           throw new BadCredentialsException("Bad credentials");
//        }
        authRequest.eraseCredentials();
    }

    @Override
    protected UserDetails retrieveUser(
            String username,
            UsernamePasswordAuthenticationToken authRequest)
            throws AuthenticationException {

        try {
            SecurityUser user = (SecurityUser) service.loadUserByUsername(username);
//            if(user.getPhone() == null){
//                throw new SimpleException(ExceptionCode.EX_BIND_PHONE);
//            }

            return user;
        } catch (UsernameNotFoundException e) {
            logger.debug("User '" + username + "' not found");
            // If could not found username
            // we throw this exception for security
            throw new BadCredentialsException("Bad credentials");
           // throw new SimpleException(ExceptionCode.EX_HTTP_ACCESS_DENIED);

        }

    }


}
